<template>
  <div class="player-bar sprite_player">
    <div class="content wrap-v2" v-if="Object.keys(currentSong).length > 0">
      <div class="control">
        <button class="sprite_player prev" @click="changeMusic(-1)"></button>
        <button 
          class="sprite_player play" 
          :style="{ 'background-position-y': isPlaying ? '-165px' : '-204px' }"
          @click="playAudio"
        >
        </button>
        <button class="sprite_player next" @click="changeMusic(1)">
          <!-- store.dispatch('player/getSongDetailAction', 167876) -->
        </button>
      </div>

      <div class="play-info">
        <div class="image">
          <img :src="formatImageSize(currentSong.al.picUrl, 34)" alt="">
        </div>

        <div class="info">
          <div class="song">{{ currentSong.name}}
            <span class="song-name"></span>
            <a href="javascript:;" class="singer-name">{{ currentSong.ar[0].name }}</a>
          </div>

          <div class="progress">
            <a-slider 
              id="test"
              :value="sliderVal" 
              @change="sliderChange"
              @afterChange="sliderAfterChange"
              :tooltip-visible="false"
            />

            <div class="time">
              <span class="now-time">{{ formatDate(currentTime, "mm:ss") }}</span>
              <span class="divider">/</span>
              <span class="duration">{{ showDuration }}</span>
            </div>
          </div>
        </div>
      </div>

      <div class="operator">
        <div class="left">
          <button class="sprite_player btn favor"></button>
          <button class="sprite_player btn share"></button>
        </div>

        <div class="right sprite_player">
          <button class="sprite_player btn volume"></button>
          <button 
            class="sprite_player btn loop"
            :style="{backgroundPosition: transSequence}"
            @click="changeSequence"
          ></button>
          <button class="sprite_player btn playlist"></button>
        </div>
      </div>
    </div>

    <audio 
      ref="audioRef"
      @timeupdate="onTimeUpdate"
      @ended="onEnded"
    >
      <!-- <source :src="musicUrl" type="audio/ogg"> -->
      <!-- <source :src="musicUrl" type="audio/mpeg"> -->
      <!-- <p>Your browser doesn't support HTML5 audio. Here is
     a <a href="myAudio.mp4">link to the audio</a> instead.</p> -->
    </audio>
  </div>
</template>

<script lang="ts" setup>
  import { computed, nextTick, onMounted, ref, watch, watchEffect } from "vue";
  import { useStore } from "@/store";

  import { useState } from "@/hooks";
  import { formatImageSize, formatDate, getPlaySong } from "@/utils/format-utils";

  const store = useStore();
  const audioRef = ref(null);
  let currentTime = ref(0);
  let sliderVal = ref(0);
  let setIsSliderTouch = ref(false);
  let isPlaying = ref(false);
  /** 2. 从vuex取出歌曲详情、歌曲播放顺序、歌词数据、歌词索引*/
  const { 
          currentSong,
          sequence
        } = useState("player", ["currentSong", "sequence"])
  /** 3. 需要用到的值 */
  const duration = computed(() => currentSong.value.dt);   //总时长
  const showDuration = computed(() => formatDate(duration.value, "mm:ss"));  //格式化显示总时间
  // const musicUrl = computed(() => {
    // return currentSong.value.id && getPlaySong(currentSong.value.id);
    // return 'http://dl.stream.qqmusic.qq.com/C4000019sHn41iQY8b.m4a?guid=9691950573&vkey=3E5BA4E0DDBC26ECA1AA0792DDEDAC625E5DD3B2ABC6671CB54BA9A702BDADC41844A6DBDFFCEDF18A17F35FD3B4609BE8EDD6A6B2820110&uin=2313219475&fromtag=66';
  // });
  const transSequence = computed(() => {
    switch (sequence.value) {
      case 1:
        return "-66px -248px";
      case 2:
        return "-66px -344px";
      default:
        return "-3px -344px"
    }
  })

  onMounted(() => {
    /** 1. 获取歌曲详情保存redux中  写死参数(ids)：29567191*/
    store.dispatch("player/getSongDetailAction", 29567191);
  });

  watch(currentSong, (newVal, oldVal) => {
    console.log("currentSongwatch", newVal, oldVal.id, audioRef.value);
    audioRef.value.src = getPlaySong(newVal.id)
    if (oldVal.id) {
      // 9.1 改变当前歌曲时，play()返回一个promise，如果能播放成功播放状态设为true，反之false；
      audioRef.value?.play().then(res => {
        isPlaying.value = true;
      }).catch(err => {
        isPlaying.value = false;
      });
    }
  });

  /**4. 播放音乐 */
  const playAudio = () => {
    isPlaying.value ? audioRef.value.pause() : audioRef.value.play();
    isPlaying.value = !isPlaying.value;
  };

  /**5. 监听当前的播放时间回调函数  转为毫秒 */
  const onTimeUpdate = (e) => {

    // 6.1滑动时不允许设置了/不在滑动时设置
    if (!setIsSliderTouch.value) {
      // 5.1显示播放时间
      currentTime.value = e.target.currentTime * 1000;
      // 随着播放改变当前播放进度条  sliderVal是整数值*100
      sliderVal.value = currentTime.value / duration.value * 100;
    }
  };

  /**10. 歌曲播放结束 */
  const onEnded = () => {
    if (sequence.value === 2) { 
      audioRef.value.currentTime = 0;
      audioRef.value.play();
    } else {
      store.dispatch("player/changeSongIndexAndSongAction", 1)
    }
  };

  /**6.手柄滑动改变播放进度 */
  const sliderChange = (value: number) => {
    setIsSliderTouch.value = true;

    //滑动时 设置播放进度条&播放时间
    sliderVal.value = value;
    currentTime.value = value / 100 * duration.value;
  };
  const sliderAfterChange = (value: number) => {
    // 确定播放时间给audio，因为audio的currentTime属性单位是秒所以 /1000；
    audioRef.value.currentTime = value / 100 * duration.value / 1000;
    // 结束/松开滑动进度条
    setIsSliderTouch.value = false;

    /**7. 进度条松开时如果是暂停状态，就播放； */
    if (!isPlaying.value) {
      playAudio();
    }
  };

  /**8. 改变播放顺序 0/顺序 1/随机 2/单曲 */
  const changeSequence = () => {
    let newSequence = sequence.value + 1;
    if (newSequence > 2) {
      newSequence = 0;
    }
    store.commit("player/changeSequence", newSequence)
  };

  /**9. 下一首&上一首 */
  const changeMusic = (tag) => {
    store.dispatch("player/changeSongIndexAndSongAction", tag)
  };

  
</script>

<style lang="less" scoped>
@import './index.less';
</style>